package ebedynky.controllers;

import ebedynky.beans.Administrator;
import ebedynky.services.AdministratorService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Ondrej David (davidon1)
 */
@Controller
public class AdministratorController {

    /**
     * Fetches the Administrator adding page when requested.
     * @param model data holder for this view
     * @return string representing page location
     */
    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public String getCreateForm(Model model) {
        model.addAttribute(new Administrator());
        return "admin/createForm";
    }

    /**
     * Extracts the Administrator data from the form,
     * validates them and stores them into the db.
     * @param administrator data from the form
     * @param result data binding result
     * @return string representing next (success/failure) page location
     */
    @RequestMapping(value = "/admin", method = RequestMethod.POST)
    public String create(@Valid Administrator administrator, BindingResult result) {
        if (result.hasErrors()) {
            return "admin/createForm";
        }
        AdministratorService as = new AdministratorService();
        administrator.setRoles("admin");
        as.addAdministrator(administrator);
        return "redirect:/adminView/";

    }

    /**
     * Returns a page with a list of administrators currently available in the db.
     * @return string representing next page location
     */
    @RequestMapping(value = "/adminView", method = RequestMethod.GET)
    public ModelAndView getView() {
        AdministratorService as = new AdministratorService();
        List<Administrator> list = as.getAllAdministrators();
        StringBuilder sb = new StringBuilder();
        for (Administrator a : list) {
            sb.append(a.getAdministratorID()).append(" ,");
        }
        String res = sb.toString();
        Map<String, String> m = new HashMap<String, String>();
        m.put("result", res);
        return new ModelAndView("admin/view", m);
    }
}
